from colorama import Fore, Back, Style
import utils
from api import ChanAPI

class Monitor:

    def __init__(self, board):
        
        self.board = board
        self.newest = 0
        self.old = 0
        self.api = ChanAPI(self.board)

    def __print_details(self, no):

        ''' clean and format the to be printed post ''' 
        
        print(Fore.BLUE +f"=== New Thread Posted {self.board} thread no:{no} ===")
        print(Style.RESET_ALL)
        
        r = self.api.getThread(no)
        
        if "sub" in r["posts"][0]:
             title = utils.cleantrash(r["posts"][0]["sub"])
             print(title)

        if "com" in r["posts"][0]:
            comment = utils.cleantrash(r["posts"][0]["com"])
            print(comment) 
        print("\n")

    def watch(self):
        ''' Find the newest thread and prints its details ''' 

        r = self.api.getCatalog()
        l = utils.getThreadList(r)
        l.sort()
        self.newest_thread = l[-1]
        
        if self.newest_thread > self.old:

            self.old = self.newest_thread
            self.newset_thread = l[0]

            self.__print_details(self.newest_thread)
